package com.example.springboot.common.aspect;

import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.ArrayUtils;
import com.example.springboot.common.annotation.SysLog;
import com.example.springboot.globalutils.SysLogEntity;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamSource;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

@Aspect
@Component
@Slf4j
public class SysLogAspect {

    private static final Logger LOGGER = LoggerFactory.getLogger(SysLogAspect.class);

    @Autowired
    private ObjectMapper objectMapper;

    private final Class<?>[] defaultExclude = {ServletResponse.class, ServletRequest.class, InputStreamSource.class};

    //通过 注解方式注入到切面
    @Pointcut("@annotation( com.example.springboot.common.annotation.SysLog)")
    public void sysbLog() {
    }


    /**
     * 环绕通知
     *
     * @param joinPoint
     * @return
     * @throws Throwable
     */
    @Around("sysbLog()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        //记录请求开始时间
        long startTime = System.currentTimeMillis();
        //获取当前请求对象
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //记录请求信息(通过Logstash传入Elasticsearch)
        SysLogEntity webLog = new SysLogEntity();
        Object result = joinPoint.proceed();
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        //获取当前请求方法
        Method method = methodSignature.getMethod();
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = signature.getName();
        SysLog syslog = method.getAnnotation(SysLog.class);
        webLog.setDescription(syslog.value());
        long endTime = System.currentTimeMillis();
        String urlStr = request.getRequestURL().toString();
        webLog.setBasePath(StrUtil.removeSuffix(urlStr, URLUtil.url(urlStr).getPath()));
        //请求IP
        webLog.setIp(request.getRemoteUser());
        //请求方法
        webLog.setMethod(className + "." + methodName + "()");
        //请求参数
        final Class<?>[] parameterTypes = methodSignature.getParameterTypes();
        Object[] args = joinPoint.getArgs();
        final boolean hasArgs = !ArrayUtils.isEmpty(parameterTypes);
        if (hasArgs) {

            final Class<?>[] exclude = syslog.exclude();
            Class<?> clazz;
            final int length = parameterTypes.length;
            final List<Object> realArgs = new ArrayList<>();
            for (int i = 0; i < length; i++) {
                clazz = parameterTypes[i];
                if (inExclude(clazz, exclude)) {
                    continue;
                }
                realArgs.add(args[i]);
            }
            final String params = realArgs.isEmpty() ? null : objectMapper.writeValueAsString(realArgs);
            webLog.setParameter(params);
            //请求结果
            webLog.setResult(result);
            //请求时间
            webLog.setStartTime(startTime);
            webLog.setSpendTime((int) (endTime - startTime));

            //请求地址
            webLog.setUri(request.getRequestURI());
            webLog.setUrl(request.getRequestURL().toString());

            LOGGER.info("{}", JSONUtil.parse(webLog));

            //保存到数据库

        }
        return result;
    }


    private boolean inExclude(Class<?> type, Class<?>[] exclude) {
        for (final Class<?> clazz : defaultExclude) {
            if (clazz.isAssignableFrom(type)) {
                return true;
            }

        }
        for (Class<?> clazz : exclude) {
            if (clazz.isAssignableFrom(type)) {
                return true;
            }
        }
        return false;
    }
}
